﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TSV.Models;
using TSV.Models.Entities;
using TSV.Library.Common;
using TSV.Library.Attributes;
using System.Configuration;
using TSV.Library.Utils;


namespace TSV.Controllers
{
    public class OrderViewController : BaseViewController
    {
        private PartnerDao partnerDao = new PartnerDao();
        private PaymentDao paymentDao = new PaymentDao();
        //
        // GET: /OrderView/

        public ActionResult Index()
        {
            List<Order> list = GetOrderList();
            string total = string.Empty;
            double dtotal = 0;
            foreach (Order item in list)
            {
                if (item.SubTotal == 0)
                {
                    total = "Call";
                    break;
                }
                else
                {
                    dtotal += item.SubTotal;
                }
            }

            if (total != "Call")
            {
                total = String.Format("{0:0,0} đ", dtotal);
            }

            ViewData["Total"] = total;
            return View(list);
        }


        public ActionResult AddToCard(string id)
        {
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            if (orderCookie == null)
            {
                orderCookie = new HttpCookie(Constants.ORDER_COOKIE);
            }
            int tempID = 0;
            try
            {
                tempID = Int32.Parse(id);
            }
            catch
            {
                tempID = 0;
            }


            Partner obj = partnerDao.GetPartnerByID(tempID);
            if (obj != null)
            {
                List<Order> list = GetOrderList();
                //"id-sl-pos#id-sl-pos"
                Order order = new Order();
                order.Id = obj.ID;
                order.ProductName = obj.PartnerName;
                order.Quantity = 1;
                order.Position = list.Count + 1;

                Order existOrder = list.Where(c => c.Id == obj.ID).FirstOrDefault<Order>();
                if (existOrder != null)
                {
                    existOrder.Quantity = existOrder.Quantity + 1;
                }
                else
                {
                    list.Add(order);
                }

                AddToCookie(list);
                return RedirectToAction("Index", "OrderView");
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult UpdateList(FormCollection collection)
        {
            List<Order> list = GetOrderList();
            int quantity = 0;
            foreach (Order item in list)
            {
                if (int.TryParse(collection["txt_" + item.Id], out quantity))
                {
                    item.Quantity = quantity;
                    item.SubTotal = item.Price * quantity;
                }
            }

            AddToCookie(list);

            return RedirectToAction("Index", "OrderView");
        }
        private void AddToCookie(List<Order> list)
        {
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            if (orderCookie == null)
            {
                orderCookie = new HttpCookie(Constants.ORDER_COOKIE);
            }

            orderCookie.Value = string.Empty;
            foreach (Order item in list)
            {
                orderCookie.Value += item.Id + "~" + item.ProductName + "~" + item.Quantity + "~" + item.Position + "#";
            }


            orderCookie.Value = orderCookie.Value.TrimEnd('#');
            orderCookie.Expires = DateTime.Now.AddDays(90d);
            Response.Cookies.Add(orderCookie);

        }

        public ActionResult Delete(int id)
        {

            List<Order> list = GetOrderList();

            Order order = list.Where(c => c.Id == id).FirstOrDefault<Order>();
            list.Remove(order);
            AddToCookie(list);
            return RedirectToAction("Index", "OrderView");
        }

        private List<Order> GetOrderList()
        {
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            try
            {
                List<Order> list = new List<Order>();
                if (orderCookie != null)
                {
                    if (!string.IsNullOrEmpty(orderCookie.Value))
                    {
                        string[] products = orderCookie.Value.Split('#');
                        foreach (string product in products)
                        {
                            string[] prop = product.Split('~');
                            Order cookieOrder = new Order();
                            cookieOrder.Id = int.Parse(prop[0]);
                            cookieOrder.Quantity = int.Parse(prop[2]);
                            cookieOrder.Position = int.Parse(prop[3]);

                            Partner partner = partnerDao.GetPartnerByID(cookieOrder.Id);
                            cookieOrder.Image = partner.Logo;
                            cookieOrder.ProductName = partner.PartnerName;
                            cookieOrder.Price = partner.CurrentPrice.HasValue ? partner.CurrentPrice.Value : 0;
                            cookieOrder.SubTotal = (cookieOrder.Price * cookieOrder.Quantity);
                            list.Add(cookieOrder);
                        }
                    }
                }

                return list;
            }
            catch
            {
                orderCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(orderCookie);
                return new List<Order>();
            }
        }
        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListJQGrid()
        {
            //grid constant => duy hung

            List<Order> list = GetOrderList();

            if (list != null && list.Count > 0)
            {

                #region JQGrid Params
                string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
                string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
                int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
                int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
                #endregion

                int totalRecords = list.Count();
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
                int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
                var finalList = list.OrderBy(c => c.Position).ToList<Order>();

                var jsonData = new
                {
                    total = totalPages,
                    page = currentPage,
                    records = totalRecords,
                    rows = (
                        from m in finalList
                        select new
                        {
                            i = m.Id,
                            cell = new string[] {
                            m.Id.ToString(),
                            "<img src=\" " + Constants.PHOTO_PATH_ROOT_PARTNER + m.Image + " \" style=\"width:80px;height:80px\"/>",                            
                            "<a href= \"" + FRouter._("sanpham",m.Id.ToString(),m.ProductName) + "\">" + m.ProductName + "</a>",                            
                            m.Price == 0 ? "Call" : String.Format("{0:0,0} đ", m.Price),
                            "<input type=\"text\" id=\"txt_" + m.Id + "\" name=\"txt_" + m.Id + "\" style=\"width:30px;text-align:center\" value='" + m.Quantity.ToString() + "' />" ,
                            m.SubTotal == 0 ? "Call" : String.Format("{0:0,0} đ", m.SubTotal),
                            m.Position.ToString(),
                            "<a href='/OrderView/Delete/" + m.Id.ToString() + "' title=\"Xóa\" onclick=\"return confirm('Bạn có chắc là bạn muốn xóa ?')\">Xóa</a>"
                            }
                        }
                    ).ToArray()
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else
                return null;
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListJQGridPayment()
        {
            //grid constant => duy hung

            List<Order> list = GetOrderList();

            if (list != null && list.Count > 0)
            {

                #region JQGrid Params
                string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
                string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
                int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
                int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
                #endregion

                int totalRecords = list.Count();
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
                int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
                var finalList = list.OrderBy(c => c.Position).ToList<Order>();

                var jsonData = new
                {
                    total = totalPages,
                    page = currentPage,
                    records = totalRecords,
                    rows = (
                        from m in finalList
                        select new
                        {
                            i = m.Id,
                            cell = new string[] {
                            m.Id.ToString(),
                            "<img src=\" " + Constants.PHOTO_PATH_ROOT_PARTNER + m.Image + " \" style=\"width:80px;height:80px\"/>",                            
                            "<a href= \"" + FRouter._("sanpham",m.Id.ToString(),m.ProductName) + "\">" + m.ProductName + "</a>",                            
                            m.Price == 0 ? "Call" : String.Format("{0:0,0} đ", m.Price),
                            m.Quantity.ToString(),
                            m.SubTotal == 0 ? "Call" : String.Format("{0:0,0} đ", m.SubTotal),
                            m.Position.ToString()                            
                            }
                        }
                    ).ToArray()
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else
                return null;
        }

        //
        // GET: /OrderView/

        public ActionResult Payment()
        {
            List<Order> list = GetOrderList();
            string total = string.Empty;
            double dtotal = 0;
            foreach (Order item in list)
            {
                if (item.SubTotal == 0)
                {
                    total = "Call";
                    break;
                }
                else
                {
                    dtotal += item.SubTotal;
                }
            }

            if (total != "Call")
            {
                total = String.Format("{0:0,0} đ", dtotal);
            }

            ViewData["Total"] = total;

            //List<string> paymentList = new List<string>();
            //paymentList.Add("Thanh toán toàn bộ");
            //paymentList.Add("Tạm ứng");            
            //ViewData["PaymentType"] = new SelectList(paymentList);

            return View();
        }

        [HttpPost]
        public ActionResult Payment(FormCollection collection)
        {
            Message msg = null;

            Payment payment = new Payment();
            payment.Name = collection["Name"];
            payment.Address = collection["Address"];
            payment.Phone = collection["Phone"];
            payment.Email = collection["Email"];
            payment.Note = collection["Note"];
            payment.PaymentType = byte.Parse(collection.GetValues("Payment")[0]);
            payment.CreateDate = DateTime.Now;

            //Check capcha here
            if (collection["txtCapcha"] == (string)TempData["CaptchaValue"])
            {
                List<Order> list = GetOrderList();
                msg = paymentDao.Insert(payment, list);
                if (msg.MsgType == MessageType.Info)
                {
                    try
                    {
                        //Clear Cookie
                        HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
                        orderCookie.Value = string.Empty;
                        orderCookie.Expires = DateTime.Now.AddDays(90d);
                        Response.Cookies.Add(orderCookie);

                        string from_email = ConfigurationManager.AppSettings["from_email"];
                        string host = ConfigurationManager.AppSettings["mailserver_host"];
                        string port = ConfigurationManager.AppSettings["mailserver_port"];
                        string poster = "Đặt hàng điện tử";
                        string subject = "Thông tin từ Đặt hàng điện tử";
                        string body = "Chào bạn <b>" + payment.Name + "</b>,<br/><br/>";
                        body += "Bạn đã đặt hàng thành công trên website vuonthieunhi.com .<br/><br/>";
                        body += "Hàng bạn đã đặt gồm có:<br/><br/>";
                        double dtotal = 0;
                        string strtotal = string.Empty;
                        foreach (Order item in list)
                        {
                            body += "-" + item.Quantity + " " + item.ProductName + ", giá:" + (item.SubTotal == 0 ? "Call" : String.Format("{0:0,0} đ", item.SubTotal)) + "<br/><br/>";
                            dtotal += item.SubTotal;
                            if (item.SubTotal == 0 && strtotal != "Call")
                            {
                                strtotal = "Call";
                            }
                        }

                        if (strtotal != "Call")
                        {
                            strtotal = String.Format("{0:0,0} đ", dtotal);
                        }
                        body += "<b>Tổng tiền: " + strtotal + "</b><br/><br/>";
                        body += "Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.<br/><br/>";
                        body += "Cảm ơn bạn đã quan tâm tới dịch vụ của chúng tôi";
                        WebUtils.SendMail(host, port, from_email, poster, payment.Email, "", subject, body);
                    }
                    catch
                    { }
                    TempData["MessageSuccess"] = "Bạn đã đặt hàng thành công trên website vuonthieunhi.com !";
                    return Redirect("/thong-bao.html");
                }
                else
                {
                    return View();
                }

            }
            else
            {
                msg = new Message(MessageConstants.E0042, MessageType.Error);
                ShowAlertMessage(msg);
                return View(payment);
            }
        }
    }
}
